package org.lzy.shop.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.adapter.CouponsHomeAdapter
import org.lzy.shop.adapter.SubmitOrderGoodsAdapter
import org.lzy.shop.address.AddressListActivity
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.cart.CartItem
import org.lzy.shop.databinding.ActivitySubmitorderBinding
import org.lzy.shop.datas.DataDTO
import org.lzy.shop.datas.Goods
import org.lzy.shop.datas.GoodsInfo
import org.lzy.shop.datas.Spec
import org.lzy.shop.datas.SubmitOrderNewRequest
import org.lzy.shop.order.PayOrderActivity
import org.lzy.shop.response.UserCoupon
import org.lzy.shop.viewmodel.SubmitOrderModel

/**
 * 提交订单
 */
class SubmitOrderActivity: BaseMvvmActivity<ActivitySubmitorderBinding, SubmitOrderModel>({ ActivitySubmitorderBinding.inflate(it)}) {
    var goodsID = 0

    var addressID = 0
    var goodsTitle: String? = null
    var goodsPic: String? = null
    var goodsSpec: String? = null
    var goodsStock: String? = null

    var goodsPrice: String? = null
    var goodsnum: String? = null

    private var userCouponList: MutableList<UserCoupon>?=null

    //存多个选中的商品
    private var selectedCartItems: List<CartItem>? = null

    //用户选择的优惠券ID
    private var selectedCouponId: Int = 0

    private val submitOrderGoodsAdapter: SubmitOrderGoodsAdapter by lazy { SubmitOrderGoodsAdapter() }



    override fun initView() {
        if (intent.extras != null) {
            val bundle = intent.extras
            // 获取单个商品信息
            bundle?.let {
                goodsID = it.getInt(Constant.GOODID, 0)
                goodsTitle = bundle.getString(Constant.GOODSTITLE)
                goodsPic = bundle.getString(Constant.GOODPIC)
                goodsPrice = bundle.getString(Constant.GOODSPRICE)
                goodsnum = bundle.getString(Constant.GOODSNUM)
                goodsSpec = bundle.getString(Constant.GOODSSPEC)
                goodsStock = bundle.getString(Constant.GOODSTOCK)
                // 获取购物车选中的多个商品
                val selectedItemsJson = bundle.getString(Constant.SELECTED_CART_ITEMS)
                if (!TextUtils.isEmpty(selectedItemsJson)) {
                    val gson = Gson()
                    val type = object : TypeToken<List<CartItem>>() {}.type
                    selectedCartItems = gson.fromJson(selectedItemsJson, type)
                }
            }

        }
        setTitleText("确认订单")
       // 初始化RecyclerView
        binding.rvSubmitorder.apply {
            layoutManager = LinearLayoutManager(this@SubmitOrderActivity, LinearLayoutManager.VERTICAL,false)
            layoutManager?.isItemPrefetchEnabled =true
            adapter = submitOrderGoodsAdapter
            setItemViewCacheSize(10)  // 减少缓存大小，根据实际情况调整
            setHasFixedSize(true)

        }
        binding.rvSubmitorder.setItemViewCacheSize(20)
        binding.rvSubmitorder.setHasFixedSize(true)
        selectedCartItems?.let {
            if (it.isNotEmpty()) {
                submitOrderGoodsAdapter.submitList(selectedCartItems)
                // 计算并显示总价
                calculateTotalPrice()
            }
        }
    }

    // 计算商品总价和合计
    private fun calculateTotalPrice() {
        var totalPrice = 0.0
        selectedCartItems?.forEach { cartItem ->
            if (cartItem.spec.isNotEmpty()) {
                val price = cartItem.spec[0].price!!.toDoubleOrNull() ?: 0.0
                totalPrice += price * cartItem.quantity
            }
        }

        // 直接在主线程更新UI
        val priceFormat = "%.2f"
        binding.goodsTotalprice.text = String.format(priceFormat, totalPrice)
        binding.goodsAllprice.text = String.format(priceFormat, totalPrice)
        binding.actConfirmOrderTvAmount.text = String.format(priceFormat, totalPrice)

    }

    override fun requestData() {

    }

    override fun onResume() {
        super.onResume()
        mViewModel.confirmOrder()
    }

    override fun initData() {
        //确认订单信息回调
        mViewModel.getConfirmOrderData.observeWithLifecycle(this){conifimOrderResponse ->
            conifimOrderResponse?.let {
                val defaultAddress = conifimOrderResponse.defaultAddress
                defaultAddress.let {
                    val addressShow= StringBuilder()
                    addressShow.append(defaultAddress.province).append(defaultAddress.city).append(defaultAddress.district)
                    binding.showAddressTxt.text = addressShow.toString()
                    binding.showSpecaddressTxt.text=defaultAddress.address
                    binding.showContract.text=defaultAddress.phone
                    addressID = defaultAddress.id
                    binding.rlAddReceiveAddress.visibility=View.GONE
                    binding.showAddressLayout.visibility=View.VISIBLE
                }
                val userCoupon = conifimOrderResponse.userCoupon
                if (userCoupon.isNotEmpty()) {
                    userCouponList=userCoupon
                }
            }
        }

        mViewModel.submitOrderAddData.observeWithLifecycle(this){submitOrderSuccessResponse ->
            dismissLoading()
            submitOrderSuccessResponse?.let {
                val bundle = Bundle()
                bundle.putString(Constant.GOODSPRICE, binding.actConfirmOrderTvAmount.text.toString())
                bundle.putInt(Constant.GOODID,submitOrderSuccessResponse.id )
                startActivity(PayOrderActivity::class.java, bundle)
            }
        }
    }



    override fun allClick() {
        binding.rlAddReceiveAddress.setOnClickListener {
            startActivity(AddressListActivity::class.java)
        }
        binding.actConfirmOrderTvSubmit.setOnClickListener {
            if (addressID == 0) {
                showToast(getResString(R.string.empty_address))
                return@setOnClickListener
            }
           submit()
        }

        //选择优惠劵
        binding.chooseCoupon.setOnClickListener {
            BottomDialog.show(object : OnBindView<BottomDialog?>(R.layout.dialog_bottom_coupon) {
                override fun onBind(dialog: BottomDialog?, view: View) {
                    val couponRv = view.findViewById<RecyclerView>(R.id.coupon_rv)
                    val couponAdapter  =
                        CouponsHomeAdapter(binding.goodsTotalprice.text.toString().toFloat())
                    couponRv.apply {
                        layoutManager=LinearLayoutManager(this@SubmitOrderActivity, LinearLayoutManager.VERTICAL, false)
                        adapter=couponAdapter
                    }
                    val list =userCouponList
                    list?.let {
                        if (list.isNotEmpty()) {
                            couponAdapter.submitList(userCouponList)
                            couponAdapter.addOnItemChildClickListener(R.id.get_now) { adapter, view, position->
                                val item = adapter.getItem(position)
                                item?.let {
                                    dialog?.dismiss()
                                    // 选中的优惠券ID
                                    selectedCouponId = item.id
                                    binding.chooseCouponName.text = item.amount.toString()
                                    val amount= item.amount
                                    val total = binding.actConfirmOrderTvAmount.text.toString().toFloat()
                                    val couponResult = total - amount
                                    binding.actConfirmOrderTvAmount.text=couponResult.toString()

                                }

                            }
                        }
                    }

                }

            }).setMaskColor("#4D000000".toColorInt())

        }

    }

    //提交订单
    private fun submit(){
        val goodsList = mutableListOf<Goods>()

        if (selectedCartItems != null && selectedCartItems!!.isNotEmpty()) {
            // 处理选中的购物车商品（可能是单个或多个）
            selectedCartItems?.forEach { cartItem ->
                // 构建规格信息
                val spec = Spec(
                    cover = "", // 可以根据实际情况设置
                    createTime = "", // 可以根据实际情况设置
                    goodsId = cartItem.goodsId,
                    id = cartItem.spec.firstOrNull()?.id ?: 0,
                    images = null, // 可以根据实际情况设置
                    name = cartItem.spec.firstOrNull()?.name,
                    price = cartItem.spec.firstOrNull()?.price,
                    sortNum = 0, // 可以根据实际情况设置
                    stock = cartItem.spec.firstOrNull()?.stock,
                    updateTime = "" // 可以根据实际情况设置
                )

                // 构建商品信息
                val goodsInfo = GoodsInfo(
                    content = "", // 可以根据实际情况设置
                    createTime = "", // 可以根据实际情况设置
                    id = cartItem.goodsId,
                    mainPic = cartItem.goodsMainPic,
                    pics = null, // 可以根据实际情况设置
                    price = cartItem.spec.firstOrNull()?.price?.toIntOrNull() ?: 0,
                    sold = 0, // 可以根据实际情况设置
                    sortNum = 0, // 可以根据实际情况设置
                    specs = null,
                    status = 1, // 可以根据实际情况设置
                    subTitle = "", // 可以根据实际情况设置
                    title = cartItem.goodsName,
                    typeId = 0, // 可以根据实际情况设置
                    updateTime = "" // 可以根据实际情况设置
                )

                // 添加商品到列表
                goodsList.add(
                    Goods(
                        count = cartItem.quantity,
                        goodsId = cartItem.goodsId,
                        goodsInfo = goodsInfo,
                        spec = spec
                    )
                )
            }
        } else {
            // 处理单个商品
            // 构建规格信息
            val spec = Spec(
                cover = "", // 可以根据实际情况设置
                createTime = "", // 可以根据实际情况设置
                goodsId = goodsID,
                id = 0, // 可以根据实际情况设置
                images = null, // 可以根据实际情况设置
                name = goodsSpec,
                price = goodsPrice,
                sortNum = 0, // 可以根据实际情况设置
                stock = goodsStock,
                updateTime = "" // 可以根据实际情况设置
            )

            // 构建商品信息
            val goodsInfo = GoodsInfo(
                content = "", // 可以根据实际情况设置
                createTime = "", // 可以根据实际情况设置
                id = goodsID,
                mainPic = goodsPic,
                pics = null, // 可以根据实际情况设置
                price = goodsPrice?.toIntOrNull() ?: 0,
                sold = 0, // 可以根据实际情况设置
                sortNum = 0, // 可以根据实际情况设置
                specs = null,
                status = 1, // 可以根据实际情况设置
                subTitle = "", // 可以根据实际情况设置
                title = goodsTitle,
                typeId = 0, // 可以根据实际情况设置
                updateTime = "" // 可以根据实际情况设置
            )

            // 添加单个商品到列表
            goodsList.add(
                Goods(
                    count = goodsnum?.toIntOrNull() ?: 1,
                    goodsId = goodsID,
                    goodsInfo = goodsInfo,
                    spec = spec
                )
            )
        }

        // 构建数据DTO
        val dataDTO = DataDTO(
            addressId = addressID,
            couponId = selectedCouponId, // 可以根据实际情况设置优惠券ID
            goodsList = goodsList,
            remark = binding.actConfirmOrderEtRemark.text.toString(),
            title = goodsTitle ?: "订单商品"
        )

        // 构建请求对象
        val request = SubmitOrderNewRequest(data = dataDTO)

        // 调用ViewModel的createOrder方法提交订单
        mViewModel.createOrder(request)
    }

    override fun onDestroy() {
        super.onDestroy()

        submitOrderGoodsAdapter.submitList(null)

        // 移除所有观察者
        mViewModel.getConfirmOrderData.removeObservers(this)
        mViewModel.submitOrderAddData.removeObservers(this)
    }
}